import { Component, OnInit, Input } from '@angular/core';
import { Catalogue } from '../book-catalogue-component/model/catalogues-model';
import { ActivatedRoute, Params } from '@angular/router';
import { catalogueService } from '../book-catalogue-component/model/catalogueService/catalogueService';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'catalogue-detail',
    templateUrl: 'catalogue-detail.component.html',
    styleUrls: ['catalogue-detail.component.scss']
})
export class CatalogueDetailComponent implements OnInit {
    @Input()
    catalogue: Catalogue;

    constructor(private bookcat: catalogueService,
        private route: ActivatedRoute,
        private locate: Location) { }

    ngOnInit() {
        this.route.params
            .switchMap((params: Params) => this.bookcat.getCatalogue(params['id']))
            .subscribe(catalogue => this.catalogue = catalogue as Catalogue)
    }

    goBack() {
        this.locate.back();
    }

    save(name: string): void {
        if (name === undefined || name === null || name.trim().length === 0) {
            alert("Please input valid value");
            return;
        }

        this.catalogue.name = name;

        if (this.bookcat.update(this.catalogue)) {
            this.goBack();
        }

    }
}